package com.l2jserver.loginserver.network.clientpackets;

import java.security.GeneralSecurityException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.crypto.Cipher;

import org.mmocore.network.ReceivablePacket;

import com.l2jserver.Config;
import com.l2jserver.loginserver.LoginController;
import com.l2jserver.loginserver.network.L2LoginClient;
import com.l2jserver.loginserver.network.serverpackets.LoginFail;
import com.l2jserver.loginserver.network.serverpackets.LoginFail.LoginFailReason;
import com.l2jserver.loginserver.network.serverpackets.LoginOk;
import com.l2jserver.loginserver.network.serverpackets.ServerList;

/**
 * @author st0rm
 */
public class RequestSCCheck extends ReceivablePacket<L2LoginClient>
{
	private static Logger _log = Logger.getLogger(RequestSCCheck.class.getName());
	private final byte[] _rec = new byte[128];
	@SuppressWarnings("unused")
	private int _session;
	private int _code;
	
	@Override
	protected boolean read()
	{
		_session = readD();
		if (_buf.remaining() >= 128)
		{
			readB(_rec);
			return true;
		}
		return false;
	}
	
	@Override
	public void run()
	{
		byte[] decrypted = null;
		try
		{
			final Cipher rsaCipher = Cipher.getInstance("RSA/ECB/nopadding");
			rsaCipher.init(Cipher.DECRYPT_MODE, getClient().getRSAPrivateKey());
			decrypted = rsaCipher.doFinal(_rec, 0x00, 0x80);
		}
		catch (GeneralSecurityException e)
		{
			_log.log(Level.INFO, "", e);
			return;
		}
		
		_code = (decrypted[0x7c] & 0xFF);
		_code |= (decrypted[0x7d] & 0xFF) << 8;
		_code |= (decrypted[0x7e] & 0xFF) << 16;
		_code |= (decrypted[0x7f] & 0xFF) << 24;
		
		if (LoginController.getInstance().isValidSecurityCode(getClient().getAccount(), _code))
		{
			if (Config.SHOW_LICENCE)
			{
				getClient().sendPacket(new LoginOk(getClient().getSessionKey()));
			}
			else
			{
				getClient().sendPacket(new ServerList(getClient()));
			}
		}
		else
		{
			getClient().sendPacket(new LoginFail(LoginFailReason.REASON_SECURITY_CARD_NUMBER_INVALID));
		}
		
	}
}
